package cn.k7g.alloy.core.objectmapper;

import cn.k7g.alloy.annotation.AlloyContent;
import cn.k7g.alloy.expose.AlloyContentHandler;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.IOException;
/**
 * 序列化alloyContent
 * @author victor-wu
 * @date 2024年4月3日
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class AlloyContentSerializer extends JsonSerializer<Object> {

    @Autowired
    private BeanFactory beanFactory;

    private AlloyContent alloyContent;
    private AlloyContentHandler alloyContentHandler;

    public AlloyContentSerializer(AlloyContent alloyContent) {
        this.alloyContent = alloyContent;
    }

    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (o == null) {
            jsonGenerator.writeNull();
            return;
        }
        jsonGenerator.writeString(getHandler().encodeObject(o));
    }

    public AlloyContentHandler getHandler() {
        if (alloyContentHandler == null) {
            alloyContentHandler = AlloyContentHandler.newInstance(beanFactory, alloyContent);
        }
        return alloyContentHandler;
    }
}
